package com.ocp.socket.server.service;

import com.alibaba.fastjson.JSON;
import com.ocp.socket.busi.milkCleanStat.bean.BaseMilkCleanStat;
import com.ocp.socket.busi.milkCleanStat.mapper.BaseMilkCleanStatMapper;
import com.ocp.socket.busi.pressureStat.bean.BasePressureStat;
import com.ocp.socket.busi.pressureStat.mapper.BasePressureStatMapper;
import com.ocp.socket.busi.warnItem.bean.BaseWarnItem;
import com.ocp.socket.busi.warnItem.mapper.BaseWarnItemMapper;
import com.ocp.socket.busi.warnMsg.bean.BaseWarnMsg;
import com.ocp.socket.busi.warnMsg.mapper.BaseWarnMsgMapper;
import com.ocp.socket.common.Constants;
import com.ocp.socket.common.bean.DevInfo;
import com.ocp.socket.common.enums.DeviceWarnEnum;
import com.ocp.socket.common.enums.MsgTypeEnum;
import com.ocp.socket.common.utils.CommonUtils;
import com.ocp.socket.common.utils.RedisUtil;
import com.ocp.socket.common.utils.SessionUtil;
import com.ocp.socket.server.vo.DataVo;
import com.ocp.socket.server.vo.MessageVo;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * @Auther: zhangzh
 * @Date: 2019/3/3 07:01
 * @Description: 气压报文处理
 * @Version: 1.0.0
 */
@Service("pressureService")
public class PressureService {

    private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());

    @Autowired
    BasePressureStatMapper basePressureStatMapper;

    @Autowired
    BaseMilkCleanStatMapper baseMilkCleanStatMapper;

    @Autowired
    BaseWarnMsgMapper baseWarnMsgMapper;

    @Autowired
    BaseWarnItemMapper baseWarnItemMapper;

    @Autowired
    private RedisUtil redisUtil;

    /******
     * 保存气压的报文信息到数据库
     * @param messageVo
     * @return
     */
    public MessageVo savePressureData(MessageVo messageVo,IoSession session){
        if(messageVo.getDataVoMap().size() < 1){
            logger.info("当前气压没有配置线路！");
            return messageVo;
        }
        Map<String,String> baseWarnMsgMap = new HashMap<String,String>();
        Map<String,Integer> baseWarnMsgTimesMap = new HashMap<String,Integer>();
        Map<String,BaseWarnItem> baseWarnItemMap = new HashMap<String,BaseWarnItem>();
        //获取设备信息
        DevInfo devInfo = (DevInfo) session.getAttribute(Constants.ATTRIBUTE_KEY_AUTH);
        //根据奶厅ID获取当前挤奶清洗状态信息
        BaseMilkCleanStat baseMilkCleanStat = baseMilkCleanStatMapper.getMilkCleanLineCodeByHallId(devInfo.getHallId());
        //奶厅下已有且未结束的报警信息
        List<BaseWarnMsg> baseWarnMsgList =  baseWarnMsgMapper.getBaseWarnMsgListByMilkHallId(devInfo.getHallId());
        for(BaseWarnMsg baseWarnMsg : baseWarnMsgList){
            baseWarnMsgMap.put(baseWarnMsg.getWarnCode(),baseWarnMsg.getId());
            baseWarnMsgTimesMap.put(baseWarnMsg.getWarnCode(),baseWarnMsg.getEndTimes());
        }
        baseWarnMsgList.clear();

        //根据奶厅查询已配置的报警信息项
        List<BaseWarnItem> baseWarnItemList = baseWarnItemMapper.getBaseWarnItemListByMilkHallId(devInfo.getHallId());
        for(BaseWarnItem baseWarnItem : baseWarnItemList){
            baseWarnItemMap.put(baseWarnItem.getWarnCode(),baseWarnItem);
        }
        baseWarnItemList.clear();

        /****
         * W011 挤奶时真空压力波动大
         * 奶厅已配置该报警
         * 报警关键因素 真空压力
         */
        BaseWarnMsg baseWarnMsg = null;
        if(baseWarnItemMap.get("W011")!=null  && messageVo.getDataVoMap().get("L01") != null){
            Double t1Val = Double.valueOf(messageVo.getDataVoMap().get("L01").getVal());

            //挤奶 并且超过20分钟
            if(baseMilkCleanStat != null && "L01".equals(baseMilkCleanStat.getLineCode()) && baseWarnItemMap.get("W001").getIgnoreTimes()<baseMilkCleanStat.getRunTimes()){
                if(t1Val < baseWarnItemMap.get("W011").getMinVal() || t1Val > baseWarnItemMap.get("W011").getMaxVal()){
                    messageVo.getDataVoMap().get("L01").setRunStat("0");
                    messageVo.getDataVoMap().get("L01").setRunStatDesc("运行异常");
                    if(baseWarnMsgMap.get("W011") == null){
                        CommonUtils.insertBaseWarnMsg(session,baseWarnMsgMapper,"W011",baseWarnItemMap,messageVo,devInfo,messageVo.getSn(),"L01", redisUtil,DeviceWarnEnum.AIRP.getDeviceCode());
                    }else{
                        baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get("W011"));
                    }
                }else{
                    if(baseWarnMsgMap.get("W011") != null ){
                        if(baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get("W011")>10){
                            CommonUtils.updateBaseWarnMsgEndTimeById(session,baseWarnMsgMapper,baseWarnMsgMap.get("W011"),messageVo.getDataTime(),devInfo.getSnNo(),devInfo.getOrgId());
                        }else{
                            baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get("W011"));
                        }
                    }
                }
            }
        }

        /****
         * W013 空压机压力小
         * 奶厅已配置该报警
         * 报警关键因素 空压机压
         */
        if(baseWarnItemMap.get("W013")!=null && messageVo.getDataVoMap().get("W013") != null){
            Double t2Val = Double.valueOf(messageVo.getDataVoMap().get("L02").getVal());
            //有挤奶信号或者清洗信号时
            if(baseMilkCleanStat != null && "L01".equals(baseMilkCleanStat.getLineCode())  || "L02".equals(baseMilkCleanStat.getLineCode())){
                if(t2Val < baseWarnItemMap.get("W011").getMinVal() ){
                    messageVo.getDataVoMap().get("L02").setRunStat("0");
                    messageVo.getDataVoMap().get("L02").setRunStatDesc("运行异常");
                    if(baseWarnMsgMap.get("W013") == null){
                        CommonUtils.insertBaseWarnMsg(session,baseWarnMsgMapper,"W013",baseWarnItemMap,messageVo,devInfo,messageVo.getSn(),"L02", redisUtil,DeviceWarnEnum.AIRP.getDeviceCode());
                    }else{
                        baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get("W013"));
                    }
                }else{
                    if(baseWarnMsgMap.get("W013") != null ){
                        if(baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get("W013")>10){
                            CommonUtils.updateBaseWarnMsgEndTimeById(session,baseWarnMsgMapper,baseWarnMsgMap.get("W013"),messageVo.getDataTime(),devInfo.getSnNo(),devInfo.getOrgId());
                        }else{
                            baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get("W013"));
                        }
                    }
                }
            }
        }

        Map<String,DataVo> dataVoMap = messageVo.getDataVoMap();
        BasePressureStat basePressureStat = null;
        List<BasePressureStat> returnValList = new ArrayList<BasePressureStat>();
        for(String key : dataVoMap.keySet()){
            DataVo dataVo =dataVoMap.get(key);
            basePressureStat = new BasePressureStat();

            basePressureStat.setDataTime(messageVo.getDataTime());
            basePressureStat.setLineCode(key);
            if(baseMilkCleanStat != null){
                basePressureStat.setMilkCleanLine(baseMilkCleanStat.getLineCode());
            }
            basePressureStat.setNowVal(Double.valueOf(dataVo.getVal()));
            basePressureStat.setUint(dataVo.getUnit());
            basePressureStat.setRunStat(dataVo.getRunStat());
            basePressureStat.setRunStatDesc(dataVo.getRunStatDesc());
            basePressureStat.setSnNo(messageVo.getSn());
            basePressureStatMapper.insertBasePressureStat(basePressureStat);
            returnValList.add(basePressureStat);
        }
        //发送消息
        logger.debug("气压发送app的Json:"+JSON.toJSON(returnValList).toString());
        SessionUtil.sendAppUserMsgByOrgId(session,devInfo.getOrgId(),CommonUtils.toMsg(MsgTypeEnum.E.getTypeCode(),messageVo.getSn(),messageVo.getDataTime(),JSON.toJSON(returnValList).toString()));
        returnValList.clear();
        //发送该牧场的报警总数
        Map <String,Integer> warnCntMap = new HashMap<String,Integer>();
        warnCntMap.put("orgWarnCnt",baseWarnMsgMapper.getWarnMsgCntByMilkOrgId(devInfo.getOrgId()));
        SessionUtil.sendAppUserMsgByOrgId(session,devInfo.getOrgId(),CommonUtils.toMsg(MsgTypeEnum.J.getTypeCode(),messageVo.getSn(),messageVo.getDataTime(),JSON.toJSON(warnCntMap).toString()));
        return messageVo;
    }

}
